<?php
namespace app\admin\controller;

use app\common\model\UserType;
use app\common\model\AdminUser as AdminUserModel;
use think\Db;
/**
 * 管理员控制器
 * Class Adminuser
 * @package app\index\controller
 */
class Adminuser extends Base
{
    /**
     * [index  管理员用户管理]
     * @return mixed|string
     * @author [C。]
     */
    public function getIndex()
    {
        $model = new AdminUserModel();

        $data = input('param.');
        $map = [];
        if (is_array($data)) {
            if (!empty($data['key']))
                $map['username'] = ['like', "%" . $data['key'] . "%"];
        }
        $this->getPageAndSize($data);
        $user = $this->user;
        try {
            $count = $model->getAdminUserCountByCondition($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getAdminUserByConditon($map, $this->from, $this->size);
        } catch (\Exception $e) {
            systembug($e->getMessage(),1,'admin/adminuser/getIndex');
            return admin_json(-1,'获取失败');
        }

        writelog('查看管理员列表',0,$user);

        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }

    /**
     * [userAdd 添加用户]
     * @return [type] [description]
     * @author [C。]
     */
    public function postAdd()
    {
        $model = new AdminUserModel();
        $type = input('param.type');
        $user = $this->user;
        if ($type == 1)
        {
            $param = input('post.');
            $param['password'] = md5(md5($param['password']) . config('admin.adminuser_password_halt'));
            //验证（待处理）

            //判断用户名是否已经注册
            $adminuser = $model->get(['username' => $param['username']]);
            if (!empty($adminuser))
                return admin_json(-2,'用户名已注册');

            try {
                $param['token'] = '';
                $id = $model->addAdminUser($param);
                if($id)
                    Db::name('auth_group_access')->insert(['uid' => $id, 'group_id' => $param['groupid']]);

            } catch (\Exception $e) {
                systembug($e->getMessage(),1,'admin/adminuser/postAdd');
                return admin_json(-1,'添加用户失败');
            }

            writelog( '管理员【' . $param['username'] . '】添加成功',0,$user);

            return admin_json(1,'添加管理员用户成功');
        }

        $role = new UserType();
        return admin_json(1,'获取成功', $role->getRole());
    }


    /**
     * [edit  编辑管理员用户]
     * @author [C。]
     * @return array|mixed
     */
    public function postEdit()
    {
        $model = new AdminUserModel();
        $type = input('post.type');
        $param = input('post.');
        $user = $this->user;
        if ($type == 1)
        {
            try {
                $param['npassword'] = md5(md5($param['npassword']) . config('admin.adminuser_password_halt'));
                $data = array(
                    'id'=>$param['id'],
                    'password'=>$param['npassword']
                );
                $model->editAdminUser($data);

            } catch (\Exception $e) {
                systembug($e->getMessage(),1,'admin/adminuser/postEdit?type=1');
                return admin_json(-1,$e->getMessage());
            }
            writelog( '管理员【' .$user['username'] . '】重置'.$param['id'].'密码成功',0,$user);
            return admin_json(1,'修改密码成功');
        }elseif($type == 2)
        {
            try {
                unset($param['token']);
                $id = $model->editAdminUser($param);
                if ($id)
                    //用户角色表
                    Db::name('auth_group_access')->where('uid', $id)->update(['group_id' => $param['groupid']]);

            } catch (\Exception $e) {
                systembug($e->getMessage(),1,'admin/adminuser/postEdit?type=2');
                return admin_json(-1,$e->getMessage());
            }
            writelog( '管理员【' . $id . '】编辑帐户管理权限成功',0,$user);
            return admin_json(1,'编辑帐户管理权限成功');
        }elseif($type == 3)
        {
            $data = input('param.');
            $result = $this->getStatus($data);
            if($result == 1)
                return admin_json(1,'已启用管理员');
            elseif($result == 2)
                return admin_json(2,'已禁止管理员');
            elseif($result == -1)
                return admin_json(-1,'操作失败');
        }
    }


    /**
     * [del   假删除  删除管理员用户]
     * @author [C。]
     * @return array
     */
    public function getDel()
    {
        $model = new AdminUserModel();
        $user = $this->user;
        $id = input('param.id');
        $res = $model->deleteFalseData(['id' => $id],['status'=>-1]);
        writelog('删除管理员--'.$id,0,$user);

        return admin_json(1,'删除管理员成功');
    }


    /**
     * [status  管理员用户状态]
     * @author [C。]
     * @return \think\response\Json
     */
    public function getStatus()
    {
        $model = new AdminUserModel();
        $data=input('param.');
        $res = $model->changeStatus(['id' => $data['id']],$data['status']);
        $user = $this->user;
        if($res)
        {
            if($data['status'] == 0)
            {
                writelog('禁用管理员状态--'.$data['id'],0,$user);
                return 2;
            }
            else
            {
                writelog('启用管理员状态--'.$data['id'],0,$user);
                return 1;
            }
        }

        return -1;
    }

    /**
     * [status  修改密码]
     * @author [C。]
     * @return \think\response\Json
     */
    public function postEditPassword()
    {
        $model = new AdminUserModel();
        $param = input('post.');
        $param['password'] = md5(md5($param['password']) . config('admin.adminuser_password_halt'));
        $user = $model->getAdminUserByCondition(['token'=>$param['token'],'password'=>$param['password']]);
        if(empty($user))
            return admin_json(-1,'原密码错误',$user);
        try {
            $param['npassword'] = md5(md5($param['npassword']) . config('admin.adminuser_password_halt'));

            $data = array(
                'id'=>$user['id'],
                'password'=>$param['npassword']
            );
            $model->editAdminUser($data);

        } catch (\Exception $e) {
            systembug($e->getMessage(),1,'admin/adminuser/postEditPassword');
            return admin_json(-1,$e->getMessage());
        }
        writelog( '管理员【' . $user['username'] . '】修改密码成功',0,$user);
        return admin_json(1,'修改密码成功');
    }
}